package com.ccteam.admin.view.fragments.common

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import com.ccteam.admin.databinding.FragmentSelectInfoBinding
import com.ccteam.admin.view.adapters.SelectItemClicked
import com.ccteam.admin.view.adapters.SelectPagingAdapter
import com.ccteam.admin.view.bean.SelectInfo
import com.ccteam.admin.view.bean.SelectInfoResult
import com.ccteam.admin.viewmodels.common.SelectViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * 选择歌手的Fragment
 */
@AndroidEntryPoint
class SelectFragment : Fragment() {

    companion object{

        /**
         * 选择歌手返回结果的KEY
         */
        const val SELECT_REQUEST_KEY = "select_key"

        const val SELECT_RESULT = "select_result"

        const val SELECT_ARTIST = 1
        const val SELECT_MUSIC = 2
        const val SELECT_ALBUM = 3
    }

    private var _binding: FragmentSelectInfoBinding? = null
    private val binding get() = _binding!!

    private val selectViewModel by viewModels<SelectViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSelectInfoBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val adapter = SelectPagingAdapter(callback)
        binding.rvArtistSelectList.adapter = adapter

        viewLifecycleOwner.lifecycleScope.launch {
            selectViewModel.artistListFlow.collectLatest {
                adapter.submitData(it)
            }
        }

        viewLifecycleOwner.lifecycleScope.launch {
            adapter.loadStateFlow.collectLatest { state ->
                binding.statusView.changeToLoadingStatus(state.refresh is LoadState.Loading)
                binding.statusView.changeToErrorStatus(state.refresh,
                    state.append.endOfPaginationReached && adapter.itemCount < 1)
            }
        }

        binding.statusView.setRetryClickListener {
            adapter.refresh()
        }
    }

    private val callback = object: SelectItemClicked {

        override fun itemSelect(item: SelectInfo) {
            setFragmentResult(
                SELECT_REQUEST_KEY, bundleOf(
                    SELECT_RESULT
                            to SelectInfoResult(item.id,item.title)))
            findNavController().navigateUp()
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }
}